var express = require('express');
var router = express.Router();
var os = require("os");
var isWin = (os.platform().indexOf('win') != -1);
var fs = require('fs')
    , gm = require('gm').subClass({imageMagick: true});
var archive = require('../utils/archive');
var loadArchive = archive.loadArchive;
var archiveLoader = archive.archiveLoader;

/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('index', {title: '首页'});
});

router.get('/gallery', function (req, res, next) {
    var imgdir = req.query.imgdir;
    var dirs = [];
    var zipfiles = [];
    var picfiles = [];
    var urlpath;
    if(!imgdir) {
        if(isWin) {
            for(var c = 67; c <= 90; ++c) {
                try  {
                    fs.readdirSync(String.fromCharCode(c) + ":/");
                    urlpath = encodeURIComponent(String.fromCharCode(c) + ":/");
                    dirs.push({
                        name: String.fromCharCode(c) + ":/",
                        path: String.fromCharCode(c) + ":/",
                        urlpath: urlpath
                    });
                } catch (e) {

                }
            }
            imgdir = "";
        } else {
            imgdir = "/";
        }
    }
    if(imgdir !== "") {
        var allfiles = fs.readdirSync(imgdir);
        for(var i in allfiles) {
            var filepath = imgdir + allfiles[i];
            try  {
                if(fs.statSync(filepath).isDirectory()) {
                    urlpath = encodeURIComponent(filepath + "/");
                    dirs.push({
                        name: allfiles[i],
                        path: filepath + "/",
                        urlpath: urlpath
                    });
                }
                if(fs.statSync(filepath).isFile()) {
                    if(/\.zip$/.test(filepath)) {
                        urlpath = encodeURIComponent(filepath);
                        zipfiles.push({
                            type: "zip",
                            name: allfiles[i],
                            path: filepath,
                            urlpath: urlpath
                        });
                    }
                }
                if(fs.statSync(filepath).isFile()) {
                    if(/\.png$/.test(filepath)) {
                        picfiles.push({
                            type: "png",
                            name: allfiles[i],
                            path: filepath
                        });
                    }else if(/\.jpg$/.test(filepath)) {
                        picfiles.push({
                            type: "jpg",
                            name: allfiles[i],
                            path: filepath

                        });
                    }else if(/\.gif$/.test(filepath)) {
                        picfiles.push({
                            type: "gif",
                            name: allfiles[i],
                            path: filepath
                        });
                    }
                }
            } catch (e) {
            }
        }
    }
    var obj = {};
    obj.title = '画廊';
    obj.dirs = dirs;
    obj.zipfiles = zipfiles;
    obj.picfiles = picfiles;
    res.render('gallery', obj);
});

router.get('/about', function (req, res, next) {
    res.render('about', {title: '关于'});
});

router.get('/showThumbnail', function (req, res, next) {
    var imgpath = req.query.imgpath;

    if(!imgpath){
        var img = fs.readFileSync('public/images/notFound.jpg');
        res.writeHead(200, {'Content-Type': 'image/jpg' });
        res.end(img, 'binary');
        return;
    }
    gm(imgpath).resize('80','80')
        .stream('jpg',function(err, stdout, stderr){
            res.writeHead('200', {'Content-Type': 'image/jpeg'});
            stdout.pipe(res);
        });
});

router.get('/showImg', function (req, res, next) {
    var imgpath = req.query.imgpath;

    if(!imgpath){
        var img = fs.readFileSync('public/images/notFound.jpg');
        res.writeHead(200, {'Content-Type': 'image/jpeg' });
        res.end(img, 'binary');
        return;
    }
    res.writeHead('200', {'Content-Type': 'image'});
    fs.createReadStream(imgpath).pipe(res);
});

router.get('/RedMangaReader', function (req, res, next) {
    var query = req.query;
    try  {
        archiveLoader = loadArchive(query);
    } catch (e) {
        res.writeHead(500, {
            'Content-Type': 'text/plain'
        });
        console.log(e.stack);
        res.end("Internal Error: \n" + e);
        return;
    }
    res.render('reader',{
        pagecount: archiveLoader.getFileList().length
    });
});

router.get('/getImage', function (req, res, next) {
    var query = req.query;
    try  {
        archiveLoader = loadArchive(query);
        var fileContent = archiveLoader.getFileByIndex(query.index);
    } catch (e) {
        res.writeHead(500, {
            'Content-Type': 'text/plain'
        });
        res.end("Internal Error: \n" + e);
        return;
    }
    res.writeHead(200, {
        'Content-Type': 'image'
    });
    res.end(fileContent);
});

module.exports = router;